
from alipay import AliPay
from django import http
from django.shortcuts import render

from django.views import View

from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from suguo_mall import settings
from utils.response_code import RETCODE
from utils.views import LoginRequiredJSONMixin


class PaymentView(LoginRequiredJSONMixin, View):
    """订单支付功能"""

    def get(self, request, order_id):
        # 查询要支付的订单
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseBadRequest('订单信息错误')
        # 创建支付宝支付对象

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string="-----BEGIN PRIVATE KEY-----\n" + 'MIIEpAIBAAKCAQEAj5+4sJ4fyhw8ruxpWk55zPh2fUDHR2mvZ6DPkA7DIOIRpeFj5WrQ7H+++RhBAQUrSczU5kb6p6s5xb01nS4Y2WCIhzhpEKxKlw6+xTP+6rqRgbt5SILVgv+Tzva81YHclOSVdqjBLxz9BtQG8vlKFh9H1dNvTaV8J6WyxD5D8GYbcsgKnHloos6eRPRBJHKpACWgUhD8keMbdpBsTPEEtI8JgqwX9lk+g0xqhzISCjs+ZmUxSpAVrAR9cNd/+BNn8xcKcAlnAFMyJ9wgjk9jlq12oYPU5Yg5RfGer+i60TPl8nDjbJUEFNCfcD4IDr+sT6Y+PM35tJErShyzUGx0LwIDAQABAoIBADMe998tuUT4PgVJMsqpCiOSAKLejs/1ZzCshZTSHFQ1A3EWw7biCVFUuwXwwxp424qeNN1uQEOz55Fhopa61K9y88Wlp4f+u2H/JpoMwtyL4cTalPXhU9wX2mWdX2NjoL8Cicy9jl2VpN5sU7jiUKOFKM2MP57Um1eFXBcLzqTfOECTHgx6bwtAxbSB6Q3JzPQSjkMMmsQSYH3ugVQgD5PEXS5V1SHDwD3Yg5kGZKrGU9tsfNjKfIXEblsL0msifwfU6ZJpfXR7Bn9BW2VEuz7OKCPLi4UCblENhPG1tHN0j4S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rfSxkeqA11Xhd1pOq/hAE1LUseB79WbCBR4OdrzVwrhKo9bkk71y7Ik+MZ7/j6ZDXd1PaGsVhg0WUBK/Fwklc5P33bfDC+JHlgwlyc858LDrYkPv5aoPCWW2nFzld4me6U+gxgFHINMcFVXpY9HwTeJ5rH2yIEcfSIohKNwhOj9c3GAJ8haUklTdLsE7aZRlcJXpxeXJbhVNyiMQDqb64+PY4JQxNSq0MY0dzt5I3I3AT+WTYOz3/f2IE22SaTpMjX4sggN31ugdDE5GhfCu/6KNFW60pEQIDAQAB' + '\n-----END PUBLIC KEY-----',
            # app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
            # app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
            # alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
        )
        print(alipay.alipay_public_key)

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


class PaymentStatusView(View):
    """保存订单支付结果"""

    def get(self, request):
        # 获取前端传入的请求参数
        query_dict = request.GET
        data = query_dict.dict()
        # 获取并从请求参数中剔除signature
        signature = data.pop('sign')

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            # app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
            # alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH,
            app_private_key_string="-----BEGIN PRIVATE KEY-----\n" + 'MIIEpAIBAAK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xaQ9TeUoo604WeUI8f9da0jJEGaAlb5GCyX3/fdg0Q62yvg6pFuMO7TbH7mRLUdN1yq8jRBnfzXqwmGZDXWG70K9KZlVA9/KupZOSV0Nh+o2AJhdvHS/JUP+L45qmUxsfdT6aaqlStMhxOhhqLVpcYBXP/O0CgYEAgV32krjBAlhK9yF5uMo32J8dVLgGWj4w3Jz/WRohifdDZfLdSi4iSyHeVEqjHiWwAjJ1v1vwfaWGaCkIdTBSKeXN6nH9JcCybBlMl4hEQJZP0i4C399coARLobFMsXlDDy+FJA+TTAh8ORhtl46vy/Tbeq1CF1Vclzsq7QpUEA0CgYBIIjpHB8vtDCkfFzM3bwBQFWlmaJ4GDba0I2c7fTcVXdJU02n6f8sysYxNAWWGcYWKh6EvJp/osPGcKS7rCIAg2kYZILWDGWJYNfPQMzzBvG4QNxLdhdyZxzRd7lh0Vnjob3cjjld6WMto+02UGzi9J+xDHqAN92GuJRkVulTsvQ==' + '\n-----END PRIVATE KEY-----',
            alipay_public_key_string='-----BEGIN PUBLIC KEY-----\n' + 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkxTVmTzlRYVCOyPj/f9BET6fWj8jLGoEhwmoagVVNBStalXy1pMeH2BrfSxkeqA11Xhd1pOq/hAE1LUseB79WbCBR4OdrzVwrhKo9bkk71y7Ik+MZ7/j6ZDXd1PaGsVhg0WUBK/Fwklc5P33bfDC+JHlgwlyc858LDrYkPv5aoPCWW2nFzld4me6U+gxgFHINMcFVXpY9HwTeJ5rH2yIEcfSIohKNwhOj9c3GAJ8haUklTdLsE7aZRlcJXpxeXJbhVNyiMQDqb64+PY4JQxNSq0MY0dzt5I3I3AT+WTYOz3/f2IE22SaTpMjX4sggN31ugdDE5GhfCu/6KNFW60pEQIDAQAB' + '\n-----END PUBLIC KEY-----',
            # app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data, signature)
        if success:
            # 读取order_id
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')
            # 保存Payment模型类数据
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 修改订单状态为待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])

            # 响应trade_id
            context = {
                'trade_id': trade_id
            }
            return render(request, 'pay_success.html', context)
        else:
            # 订单支付失败，重定向到我的订单
            return http.HttpResponseForbidden('非法请求')
